package site.isscloud.admin.controller.mqtt;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;
import site.isscloud.common.core.controller.BaseController;
import site.isscloud.common.core.domain.AjaxResult;
import site.isscloud.framework.config.MqttConfig;
import site.isscloud.project.constants.BusinessConstants;
import site.isscloud.project.mqtt.ProjectMqttService;

import java.util.HashMap;
import java.util.Map;

/**
 * MQTT控制器
 */
@RestController
@RequestMapping("/mqtt")
@ConditionalOnProperty(name = "mqtt.enabled", havingValue = "true")
public class MqttController extends BaseController {

    @Autowired
    private MqttConfig mqttConfig;

    @Autowired
    private ProjectMqttService projectMqttService;

    // ========== 业务接口 ==========

    /**
     * 发布实时数据
     */
    @PostMapping("/data/realtime")
    public AjaxResult publishRealtimeData(@RequestBody Map<String, Object> data) {
        try {
            if (!data.containsKey("timestamp")) {
                data.put("timestamp", System.currentTimeMillis());
            }

            boolean success = projectMqttService.publishRealtimeData(data);
            if (success) {
                return AjaxResult.success("实时数据发布成功");
            } else {
                return AjaxResult.error("实时数据发布失败");
            }
        } catch (Exception e) {
            logger.error("发布实时数据失败", e);
            return AjaxResult.error("实时数据发布失败: " + e.getMessage());
        }
    }

    /**
     * 发布告警数据
     */
    @PostMapping("/alarm/publish")
    public AjaxResult publishAlarmData(@RequestBody Map<String, Object> alarmData) {
        try {
            if (!alarmData.containsKey("timestamp")) {
                alarmData.put("timestamp", System.currentTimeMillis());
            }

            boolean success = projectMqttService.publishAlarmData(alarmData);
            if (success) {
                return AjaxResult.success("告警数据发布成功");
            } else {
                return AjaxResult.error("告警数据发布失败");
            }
        } catch (Exception e) {
            logger.error("发布告警数据失败", e);
            return AjaxResult.error("告警数据发布失败: " + e.getMessage());
        }
    }

    // ========== 基础MQTT操作接口 ==========

    /**
     * 发布消息
     */
    @PostMapping("/publish")
    public AjaxResult publish(@RequestParam String topic,
                              @RequestParam String message,
                              @RequestParam(defaultValue = "1") int qos) {
        try {
            boolean success = mqttConfig.publish(topic, message, qos);
            if (success) {
                return AjaxResult.success("消息发布成功");
            } else {
                return AjaxResult.error("消息发布失败，请检查MQTT连接状态");
            }
        } catch (Exception e) {
            logger.error("发布消息失败 - Topic: {}, Message: {}", topic, message, e);
            return AjaxResult.error("消息发布异常: " + e.getMessage());
        }
    }

    /**
     * 发布消息到默认主题
     */
    @PostMapping("/publish/default")
    public AjaxResult publishToDefault(@RequestParam String message,
                                       @RequestParam(defaultValue = "0") int qos) {
        try {
            boolean success = mqttConfig.publishToDefaultTopic(message, qos);
            if (success) {
                return AjaxResult.success("消息发送到默认主题成功");
            } else {
                return AjaxResult.error("消息发送失败，请检查MQTT连接状态");
            }
        } catch (Exception e) {
            logger.error("发布默认主题消息失败 - Message: {}", message, e);
            return AjaxResult.error("消息发送异常: " + e.getMessage());
        }
    }

    /**
     * 订阅主题
     */
    @PostMapping("/subscribe")
    public AjaxResult subscribe(@RequestParam String topic,
                                @RequestParam(defaultValue = "1") int qos) {
        try {
            mqttConfig.subscribe(topic, qos);
            return AjaxResult.success("主题订阅成功: " + topic);
        } catch (Exception e) {
            logger.error("订阅主题失败 - Topic: {}", topic, e);
            return AjaxResult.error("订阅主题失败: " + e.getMessage());
        }
    }

    /**
     * 取消订阅
     */
    @PostMapping("/unsubscribe")
    public AjaxResult unsubscribe(@RequestParam String topic) {
        try {
            mqttConfig.unsubscribe(topic);
            return AjaxResult.success("取消订阅成功: " + topic);
        } catch (Exception e) {
            logger.error("取消订阅失败 - Topic: {}", topic, e);
            return AjaxResult.error("取消订阅失败: " + e.getMessage());
        }
    }

    // ========== 状态查询接口 ==========

    /**
     * 检查MQTT连接状态
     */
    @GetMapping("/status")
    public AjaxResult getStatus() {
        try {
            boolean isConnected = mqttConfig.isConnected();
            String status = isConnected ? "已连接" : "未连接";
            return AjaxResult.success("MQTT连接状态", status);
        } catch (Exception e) {
            logger.error("检查MQTT状态失败", e);
            return AjaxResult.error("检查MQTT状态失败: " + e.getMessage());
        }
    }

    /**
     * 获取MQTT配置信息
     */
    @GetMapping("/config")
    public AjaxResult getConfig() {
        try {
            String configInfo = String.format(
                    "Broker: %s, ClientId: %s, DefaultTopic: %s, Connected: %s",
                    mqttConfig.getBrokerUrl(),
                    mqttConfig.getClientId(),
                    mqttConfig.getDefaultTopic(),
                    mqttConfig.isConnected()
            );
            return AjaxResult.success("MQTT配置信息", configInfo);
        } catch (Exception e) {
            logger.error("获取MQTT配置失败", e);
            return AjaxResult.error("获取MQTT配置失败: " + e.getMessage());
        }
    }

    /**
     * 获取系统支持的MQTT主题列表
     */
    @GetMapping("/topics")
    public AjaxResult getSupportedTopics() {
        try {
            String[] topics = {
                    BusinessConstants.MQTT_REALTIME_TOPIC + " - 电梯实时数据 (QoS 1)",
                    BusinessConstants.MQTT_ALARM_TOPIC + " - 电梯告警数据 (QoS 1)"
            };
            return AjaxResult.success("支持的MQTT主题列表", topics);
        } catch (Exception e) {
            logger.error("获取主题列表失败", e);
            return AjaxResult.error("获取主题列表失败: " + e.getMessage());
        }
    }
}